package com.example.tabbar.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.lifecycle.ViewModelProvider
import com.example.tabbar.databinding.FragmentSetUserBinding
import com.example.tabbar.utils.CustomSpinner
import com.junray.usermangement.R
import com.junray.usermangement.room.bean.JsonRule
import com.junray.usermangement.room.entity.Rule
import com.junray.usermangement.utils.LiveDataUtils.observeOnce
import com.junray.usermangement.utils.SessionManager
import com.junray.usermangement.viewModel.UserViewModel

@SuppressLint("UseSwitchCompatOrMaterialCode")
class SetUserFragment : Fragment() {
    private var binding: FragmentSetUserBinding? = null
    private var pwdValid:TextView? = null
    private var isUppercase: Switch? = null
    private var complex: TextView? = null
    private var pwdErrorCount :TextView? = null
    private var currentRule: Rule? = null
    private var sessionManager: SessionManager? = null
    private var currentId: Long = 0
    private var viewmodel: UserViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentSetUserBinding.inflate(inflater, container, false)
        return binding ?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
        //回显密码规则
        ruleData()

        //初始化密码规则下拉选择框
        setupPwdRule()


        onClick()

    }

    private fun initView() {
        pwdValid = binding?.etPwdValid
        isUppercase = binding?.uppercase
        complex = binding?.complex
        pwdErrorCount = binding?.pwdErrorCount

        sessionManager = SessionManager.instance
        if(sessionManager?.currentUser != null) {
            currentId = sessionManager!!.userId
        }
        viewmodel = ViewModelProvider(this)[(UserViewModel::class.java)]
    }


    private fun setupPwdRule() {
        val items = listOf("字母加数字", "数字", "特殊字符")
        val customSpinner = CustomSpinner(requireActivity(), items) { _, item ->
            complex?.text = item
        }

        customSpinner.setOnDismissListener {
            complex?.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                com.example.tabbar.R.drawable.to_down,
                0
            )
        }

        complex?.setOnClickListener {
            complex?.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                com.example.tabbar.R.drawable.to_up,
                0
            )
            val currentText = complex?.text.toString()
            val position = items.indexOf(currentText)
            if (position >= 0) {
                customSpinner.setSelectedPosition(position)
            }
            customSpinner.show(complex!!)
        }
    }

    private fun onClick() {
        binding!!.editBack.setOnClickListener {
            // 返回上一页
            parentFragmentManager.popBackStack()
        }
        binding!!.setSave.setOnClickListener {
            val pwdValid = pwdValid?.text.toString().trim()
            val isUppercase = isUppercase?.isChecked ?: false
            val complex = complex?.text.toString().trim()

            if (currentRule == null) {
                currentRule = Rule()
                currentRule!!.userId = currentId
            }
            val jsonRule = when (complex) {
                "字母加数字" -> JsonRule(isUppercase, isLowercase =true, isNumber = true, isSymbol =false)
                "数字" -> JsonRule(isUppercase, isLowercase =false, isNumber =true, isSymbol =false) // 只使用数字
                "特殊字符" -> JsonRule(isUppercase, isLowercase =false, isNumber =false, isSymbol = true) // 可以根据需要调整
                else -> JsonRule(isUppercase, isLowercase =false, isNumber =false, isSymbol =false)
            }

            //几次禁用
            val pwdFailures = if (pwdErrorCount!!.text.toString().trim { it <= ' ' }
                    .isEmpty()) 0 else pwdErrorCount!!.text.toString().trim { it <= ' ' }.toInt()

            if (pwdValid ==  "0") {
                Toast.makeText(
                    requireActivity(),
                    R.string.um_set_pwd_valid_day,
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            if (pwdFailures < 3) {
                Toast.makeText(
                    requireActivity(),
                    R.string.um_set_pwd_failures,
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            currentRule?.pwdComplex = jsonRule.toJson()
            currentRule?.pwdValid = pwdValid
            currentRule?.pwdFailures = pwdFailures

            observeOnce(viewmodel!!.getRuleCount(currentId),viewLifecycleOwner) {  count -> Int
                if (count == 0) {
                    viewmodel!!.insertRule(currentRule!!)
                    Toast.makeText(
                        requireActivity(),
                        "创建成功",
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    viewmodel!!.updateRule(currentRule!!)
                    Toast.makeText(
                        requireActivity(),
                        "编辑成功",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                sessionManager?.currentRule = currentRule
                parentFragmentManager.popBackStack()
            }
        }
        binding?.switchUppercase?.setOnClickListener {
            isUppercase?.isChecked = !isUppercase?.isChecked!!
        }
    }

    @SuppressLint("SetTextI18n")
    private fun ruleData() {
        observeOnce(viewmodel!!.getRule(currentId),viewLifecycleOwner) { rule: Rule? ->
            if (rule != null) {
                currentRule = rule
                val jsonRule = JsonRule.fromJson(rule.pwdComplex)
                pwdValid?.text = rule.pwdValid
                pwdErrorCount?.text = rule.pwdFailures.toString()
                isUppercase?.isChecked = jsonRule.isUppercase
                complex?.text = when {
                    jsonRule.isLowercase && jsonRule.isNumber && !jsonRule.isSymbol -> "字母加数字"
                    !jsonRule.isLowercase && jsonRule.isNumber && !jsonRule.isSymbol -> "数字"
                    !jsonRule.isLowercase && !jsonRule.isNumber && jsonRule.isSymbol -> "特殊字符"
                    else -> "字母加数字" // 默认选项
                }
            }

        }
    }

    companion object {
        @JvmStatic
        fun newInstance(userId: Int? = null) =
            SetUserFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }
}